﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using Fcdbas.Core.Net;
using FileTransferProtocol;


namespace FileTransferSrv
{
    public partial class frmUpdateSrv : Form
    {
        private string configPath;
        public static string LogPath;
        private SocketServer FFServer;
        private ConfigSrv config;
        private FileTransferServer fileTfSrv;
        public OnEventMessageDelegate FEvent;
       // private int FConnectionCount;
        public frmUpdateSrv()
        {
            InitializeComponent();
            LogPath = AppDomain.CurrentDomain.BaseDirectory + "Log";
        }
        private void GetIP()
        {
            string hostName = Dns.GetHostName();//本机名   
            //System.Net.IPAddress[] addressList = Dns.GetHostByName(hostName).AddressList;//会警告GetHostByName()已过期，我运行时且只返回了一个IPv4的地址   
            System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostName);//会返回所有地址，包括IPv4和IPv6   
            foreach (IPAddress ip in addressList)
            {
                cbIP.Items.Add(ip.ToString());
            }
        }
        private void frmUpdateSrv_Load(object sender, EventArgs e)
        {
            GetIP();
            configPath = AppDomain.CurrentDomain.BaseDirectory + "ConfigSrv.xml";
            config = Fcdbas.Core.Xml.XmlHelper.ToXmlFileEntity<ConfigSrv>(configPath);
            if (config == null)
                config = new ConfigSrv();
            else
            {
                this.txtDownLoadPath.Text = config.DownLoadPath;
                this.ckListernFolder.Checked = config.IsEnableRaising;
                this.txtPort.Text = config.Port.ToString();
                this.cbIP.Text = config.IP;
            }
        }
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtDownLoadPath.Text) || string.IsNullOrEmpty(txtPort.Text))
            {
                MessageBox.Show("监控目录或者端口号不能为空！");
                return;
            }
            if (FFServer == null)
            {
                fileTfSrv = new FileTransferServer(FEvent, txtDownLoadPath.Text, txtDownLoadPath.Text, config.IsEnableRaising);
                fileTfSrv.FileListChanged += new EventHandler(fileTfSrv_FileListChanged);
                FFServer = new SocketServer(CallbackThreadType.ctIOThread, fileTfSrv, DelimiterType.dtMessageTailExcludeOnReceive, Encoding.GetEncoding(1252).GetBytes("%$#@^&"), 1024 * 10, 1024 * 160);
            }
            AddListener();
            FFServer.Start();
            bsFileList.DataSource = fileTfSrv.GetDownLoadList();
            bsFileList.ResetBindings(false);
            btnStop.Enabled = true;
            btnStart.Enabled = false;
        }
        private void RefreshList()
        {
            bsFileList.DataSource = fileTfSrv.GetDownLoadList();
            bsFileList.ResetBindings(false);
        }
        void fileTfSrv_FileListChanged(object sender, EventArgs e)
        {
            if (InvokeRequired)
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    RefreshList();
                }));
            }
            else
            {
                RefreshList();
            }
        }
        private void AddListener()
        {
            if(string.IsNullOrEmpty(config.IP))
                FFServer.AddListener(String.Empty, new IPEndPoint(IPAddress.Any, int.Parse(txtPort.Text)), EncryptType.etNone, CompressionType.ctNone, null, 50, 3);
            else
                FFServer.AddListener(String.Empty, new IPEndPoint(IPAddress.Parse(config.IP), int.Parse(txtPort.Text)), EncryptType.etNone, CompressionType.ctNone, null, 50, 3);

        }
        private void btnBrows_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtDownLoadPath.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void frmUpdateSrv_FormClosing(object sender, FormClosingEventArgs e)
        {
            Fcdbas.Core.Xml.XmlHelper.ToXmlFile(config, configPath);
            if (FFServer != null && FFServer.Active)
                FFServer.Stop();
            if (fileTfSrv != null)
                fileTfSrv.SaveTranferFile();
        }
        private void btnStop_Click(object sender, EventArgs e)
        {
            FFServer.Stop();
            this.btnStart.Enabled = true;
            this.btnStop.Enabled = false;
        }
        private void txtDownLoadPath_TextChanged(object sender, EventArgs e)
        {
            this.config.DownLoadPath = txtDownLoadPath.Text;
        }

        private void txtPort_TextChanged(object sender, EventArgs e)
        {
            this.config.Port = int.Parse(txtPort.Text);
        }

        private void ckListernFolder_CheckedChanged(object sender, EventArgs e)
        {

            this.config.IsEnableRaising = ckListernFolder.Checked;
            if(fileTfSrv != null)
                fileTfSrv.SetWatcherEnable(this.ckListernFolder.Checked);
        }

        private void cbIP_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.config.IP = cbIP.Text;
        }

        private void gvFileList_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            e.Graphics.DrawString((e.RowIndex + 1).ToString(),
               e.InheritedRowStyle.Font,
               new SolidBrush(Color.DarkBlue),
               e.RowBounds.Location.X + 15,
               e.RowBounds.Location.Y + 5);
        }

        private void cbIP_TextChanged(object sender, EventArgs e)
        {
            this.config.IP = cbIP.Text;
        }
    }
}
